<?php 
namespace MyClass;
class LoginAndRegister extends \C\Action{
	protected static $U;
	public function LoginDo(){
        if(!$_REQUEST['username']||!$_REQUEST['password']) {
            $this->error("手机或密码不能为空");
        }
        if(!$this->isMobile($_POST['username'])) {
            $this->error("手机格式不正确");
        }
        if(!$this->isPWD($_POST['password'])) {
            $this->error("密码格式不正确");
        }
		$w = array("Phone"=>$_POST['username'],'Password' => $_POST['password'],'Status' => 0);
		$info = $this->m('user')->where($w)->find();
		if($info){
			if(isset($info['Cid'])){
				$company = $this->m('company')->where("Id = " . $info['Cid'])->find();
			}else{
				$company['CompanyName']="";
			}
			$user = array(
				'id' => $info['Id'],
				'cid' => $info['Cid'],
				'pid' => $info['Pid'],
				'phone' => $info['Phone'],
				'CompanyName' => $company['CompanyName'],
                'UserPhoto' => $info['UserPhoto'],
			);
			session('UserInfo',$user);
            $this->U = session('UserInfo');
			header("Location:http://wap.chnhuacai.com");
			//$this->success("登录成功",T('Index/Index'));

		}else{
			$this->error("用户名或密码错误");
		}
	}
    public function Register(){
        $sessonss = session("UserInfo");
        if( $sessonss['phone']) {
            $wheres["phone"] = $_SESSION["UserInfo"]['phone'];
            $is=$this->m('prize_log')->where($wheres)->find();
            if($is) {
                $this->s("msg","您已抽过奖了");
                $this->s("log",$is);
                $this->s("ifcj",1);
                $this->v("choujiang/yyy");
            } else {
                $this->v("Public/Register");
            }
        }else {
            $this->v("Public/Register");
        }
    }
    public function Register2(){
        session('CheckToken',md5("huacai".time()));
        $this->s('CheckToken',session('CheckToken'));
		if(isset($_REQUEST['openid'])){
			$openid = $_REQUEST['openid'];
			$this->s("openid",$openid);
		}
        $this->v("Public/Register2");
    }
    //发送验证码接口
    public function SendVerification(){
        if(!$_POST['phone'] || !$this->isMobile($_POST['phone'])||!$_POST['Token']) {
            $data = array("error_code" => false, "msg" => "手机格式不正确"); echo(json_encode($data)); exit;
        }
        if($_POST['Token']!=session('CheckToken')) {
            $data = array("error_code" => false, "msg" => "参数错误"); echo(json_encode($data)); exit;
        }
        $Phone = $_POST['phone'];
        $ckecks = $this->CheckVerification($Phone);
        if($ckecks == 1){
            $data = array("error_code" => false, "msg" => "一分钟内不能连续发送"); echo(json_encode($data)); exit;
        }
        if($ckecks == 2){
            $data = array("error_code" => false, "msg" => "一天发送次数不能超过10次"); echo(json_encode($data)); exit;
        }
        //发送验证码
        $time = time();
        $num =rand(1000, 9999);
        $conditions['Phone'] =$Phone;
        $conditions['Num'] = $num;
        $conditions['Time'] = $time;
        $ms = array(
            'content' 	=> '【华采网】您申请的手机验证码是:'.$num.',请输入后进行验证。提示:请勿泄露给他人',//短信内容
            'mobile' 	=> $Phone,//手机号码
        );
        $sendSt = send($ms);
        $sendSt= explode(',',$sendSt);
        if($sendSt[0]!= 1) {
            $data = array("error_code" => false, "msg" => "发送失败"); echo(json_encode($data)); exit;
        };
        $results = $this->m('verification')->add($conditions);
        if($results) {
            session('CheckToken',null);
            $data = array("error_code" => 200, "msg" => "发送成功，请注意查收!"); echo(json_encode($data)); exit;
        }else{
            $data = array("error_code" => false, "msg" => "发送失败"); echo(json_encode($data)); exit;
        }
    }
    //验证码发送检查
    public function CheckVerification($Phone){
        //一分钟内不能连续发送
        $last_time = $this->m('verification')->where("Phone = " .$Phone )->order('Time desc')->find();
        if((time() - $last_time['Time']) < 60) {
            return 1;die;
        }
        //一天发送次数不能超过10次
        $start_time = strtotime(date('Y-m-d', time()));
        $end_time = $start_time + 86400;
        $condition["Time"] = array('between',$start_time .' and '. $end_time);
        $condition["Phone"] = $Phone;
        $has_nums = $this->m('verification')->where($condition)->count();
        if($has_nums >9) {
            return 2;die;
        }
//        return 3;
    }
    //注册
    public function RegisterDo() {
        if(!$this->isMobile($_POST['phone'])) {
            $data = array("error_code" => false, "msg" => "手机格式不正确");
            echo(json_encode($data));
            exit;
        }
        if(!$this->isNum($_POST['verification'])) {
            $data = array("error_code" => false, "msg" => "验证码格式不正确");
            echo(json_encode($data));
            exit;
        }
        if(!$this->isPWD($_POST['password'])) {
            $data = array("error_code" => false, "msg" => "密码格式不正确");
            echo(json_encode($data));
            exit;
        }
		if($_POST['CompanyName']==''|| !$_POST['CompanyName']) {
            $data = array("error_code" => false, "msg" => "公司名不能为空");
            echo(json_encode($data));
            exit;
        }
        $phone = $_POST['phone'];
        $verification = $_POST['verification'];
        $password = $_POST['password'];
        $CompanyName = $_POST['CompanyName'];
        //验证是否登录
        if($this->U['id']){
            $data = array("error_code" => false, "msg" => "请退出后再注册");
            echo(json_encode($data));
            exit;
        }
        //检测公司名是否已被注册
        $resultss = $this->m('company')->where("CompanyName='".$CompanyName."'")->find();
        if($resultss) {
            $data = array("error_code" => false, "msg" => "该公司名已被注册");
            echo(json_encode($data));
            exit;
        }
        //检测手机号是否已被注册
        $result1 = $this->m('user')->where('Phone = '.$phone)->count();
        if($result1) {
            $data = array("error_code" => false, "msg" => "该手机号已被注册");
            echo(json_encode($data));
            exit;
        }
        //检测验证码是否正确
        $result2 = $this->m('verification')->where('Phone = '.$phone)->order('Time desc')->find();
        if($result2['Num'] != $verification) {
            $data = array("error_code" => false, "msg" => "验证码不正确");
            echo(json_encode($data));
            exit;
        }
        if((time()-$result2['Time']) > 300) {
            $data = array("error_code" => false, "msg" => "验证码过期");
            echo(json_encode($data));
            exit;
        }
		if($_REQUEST['openid']){
			//验证openID是否存在
			$ifop = $this->m("user")->where("Openid='".$_REQUEST['openid']."'")->find();
			if($ifop){
                $data = array("error_code" => false, "msg" => "此微信号已经绑定账号");
                echo(json_encode($data));
                exit;
			}else{
				$condition['Openid'] = $_REQUEST['openid'];
			 }
		}
        //注册
			$condition['Phone'] = $phone;
			$condition['Password'] = $password;
			$condition['RegDate'] = time();
        $condition['Name'] = $_REQUEST['peoplename'];
		$comd['CompanyName'] =$CompanyName;
		$companyre = $this->m('company')->add($comd);
		if($companyre){
			
			$condition['Cid'] = $companyre;
			$result3 = $this->m('user')->add($condition);
			
			if($result3) {
				$user = array(
					'id' => $result3,
					'cid' => $condition['Cid'],
					'pid' => 0,
                    'name' =>  $condition['Name'],
					'phone' => $phone,
					'UserPhoto' => '',
                    'CompanyName' => $CompanyName,
				);
				session('UserInfo',$user);
				$this->U = session('UserInfo');
				//header("Location:http://wap.chnhuacai.com"); 
				//header("Location:http://wap.chnhuacai.com/?m=Index&a=Xzurl");
//			   $this->success("您已注册成功,请完善公司信息",T('Index/Index'));
                $data = array("error_code" => 200, "msg" => "您已注册成功,前去抽奖");
                echo(json_encode($data));
                exit;
			}else {
				$this->error("系统繁忙，请稍后再试!");
                $data = array("error_code" => false, "msg" => "系统繁忙，请稍后再试!");
                echo(json_encode($data));
                exit;
			}
		}
    }
	//微信绑定账号
	public function BindingDo(){
		if(!$_REQUEST['openid']){
			$this->error("非法操作");
		}
		 if(!$this->isMobile($_REQUEST['phone'])) {
            $this->error("手机格式不正确");
        }
        if(!$this->isNum($_REQUEST['verification'])) {
            $this->error("验证码格式不正确");
        }
		if(!$this->isPWD($_REQUEST['password'])) {
            $this->error("密码格式不正确");
        }
		$openid = $_REQUEST['openid'];
		$phone = $_REQUEST['phone'];
        $verification = $_REQUEST['verification'];
        $password = $_REQUEST['password'];
        //验证是否登录
        if($this->U['id']){
            $this->error("请退出后再注册");
        }
		 //检测是否已被注册 以及密码是否正确
        $result1 = $this->m('user')->where('Phone = '.$phone)->find();
        if(!$result1) {//如果数据库中没有此账号说明非法操作
            $this->error("非法操作");
        }else{
			if($password != $result1['Password']){
				$this->error("密码错误");
			}elseif($result1['OpenId']!=''){
			
				$this->error("此账号已绑定");
			}
		}
		 //检测验证码是否正确
        $result2 = $this->m('verification')->where('Phone = '.$phone)->order('Time desc')->find();
		
        if($result2['Num'] != $verification) {
            $this->error("验证码不正确");
        }
        if((time()-$result2['Time']) > 300) {
           $this->error("验证码过期");
        }
		//绑定
		$data = array(
			'OpenId' => $openid	
		);
		$request3 = $this->m("user")->where('Phone = '.$phone)->save($data);
		if($request3 !== false){
			/*$code = md5(rand(0,9999).time());
			$SweepstakesNumber = $this->ScSweepstakesNumber(); //获取6位不重复的数字
			$SweepstakesNumber = $this->SknHq($SweepstakesNumber);//判断数据库中是否存在;
			$ifstk = $this->m("sweepstakes")->where("Uid =".$result1['Id'])->find();//判断是否存在抽奖卷
			if(!$ifstk){
				$dataarr = array(
					'code' => $code,	
					'Uid'  =>  $result1['Id'],	
					'CreateTime' => time(),	
					'Djstatus' => 1,	
					'SweepstakesNumber' => $SweepstakesNumber,
					'MaturityTime' => strtotime(date('Y-m-d'))+24*3600,
					'Ifdel' => 1,
					'Dhstatus' => 1
					);		
				$res = $this->m("sweepstakes")->add($dataarr);//添加抽奖卷
				if($res){
					$ms = array(
						'content' 	=> '【华采网】恭喜您注册“华采网”成功！并获得品牌充电宝一个!更多机会——特等：价值10000元纪念币一套（1名）；一等：价值5000元华为手机一部(5名)；二等：价值3000元 IPAD MIN4一部(20名)，三等：价值1000元华为手环一个(50名)。具体详情http://www.chnhuacai.com/?m=News&a=NewsContent&id=29',//短信内容

						'mobile' 	=> $result1['Phone'],//手机号码
					);
				  send($ms);
				}
				
				if(!$res){
					$this->error("系统繁忙，请稍后再试!");
				}
			}*/

			$user = array(
                'id' => $result1['Id'],
                'cid' => $result1['Cid'],
                'pid' => $result1['Pid'],
                'phone' => $phone,
                'UserPhoto' => $result1['UserPhoto'],
            );
            session('UserInfo',$user);
            $this->U = session('UserInfo');
			//header("Location:http://wap.chnhuacai.com/?m=Index&a=Xzurl");
             $this->success("您已绑定成功",T('Index/Index'));
		}else{
			$this->error("绑定失败");
		}
	
	}

    //找回密码
    public function GetPassword() {
            $this->v('Public/getpassword_1');
    }
    //找回密码-验证码
    public function GetBackPasswordStep1() {
        $phone = $this->U['phone'];
        if(!$this->isNum($_POST['verification'])) {
            $this->error("验证码格式不正确");
        }
        $verification = $_POST['verification'];
        //验证是否登录
        if($this->U['id']){
            $this->error("请退出后再注册");
        }
        //检测验证码是否正确
        $result = $this->m('verification')->where('Phone = '.$phone)->order('Time desc')->find();
        if($result['Num'] != $verification) {
            $this->error("验证码不正确");
        }
        if((time()-$result['Time']) > 300) {
            $this->error("验证码过期");
        }
        $this->s('phone', $phone);
        $this->s('verification', $verification);
        $this->v("Public/getpassword_2");
    }
    //找回密码-修改密码
     public function GetBackPasswordStep2() {
         if(!$this->isNum($_POST['verification'])) {
             $this->error("验证码格式不正确");
         }
         if(!$this->isPWD($_POST['password'])) {
             $this->error("密码格式不正确");
         }
         $verification = $_REQUEST['verification'];
         $phone = $this->U['phone'];
         $password = $_POST['password'];
         //检测验证码是否正确
         $result = $this->m('verification')->where('Phone = '.$phone)->order('Time desc')->find();
         if($result['Num'] != $verification) {
             $this->error("系统繁忙");
         }
         //修改密码
         $update['Password'] = $password;
         $result = $this->m('user')->where('Phone = '.$phone)->save($update);
        if($result !== false) {
            $this->success("修改成功",T('Common/Login'));
        } else {
            $this->error("修改失败");
        }
     }
	 public function PhoneOnlyAjax(){//手机号码唯一验证
         if(!$this->isMobile($_POST['phone'])) {
             $data = array("error_code" => false, "msg" => "手机格式不正确");
             echo(json_encode($data));
             exit;
         }
			$phone = $_POST['phone'];
			$onlyhpone = $this->m('user')->where("Phone=".$phone)->count();
			if($onlyhpone){
                $data = array("error_code" => false, "msg" => "手机号已注册");
                echo(json_encode($data));
                exit;
			}else{
                $data = array("error_code" => 200, "msg" => "手机号可以用");
                echo(json_encode($data));
                exit;
			}
	}
	 public function CompanyNameOnlyAjax(){//公司名唯一验证
         if($_POST['CompanyName']=='' || !$_POST['CompanyName']) {
             echo 3;
			 exit;
         }
			$CompanyName = $_POST['CompanyName'];
			$onlyhpone = $this->m('company')->where("CompanyName='".$CompanyName."'")->find();
			if($onlyhpone){
				echo 1;
			}else{
				echo 2;
			}
		
			return;

	
	}
	public function LoginAjaxDo(){
        /*
		if(!$this->isMobile($_REQUEST['username'])){
		   echo 1;
		   exit;
        }
		*/
        if(!$this->isPWD($_POST['password'])) {
		   echo 2;
		   exit;
        }
		$w = array("Phone"=>$_POST['username'],'Password' => $_POST['password']);
		$info = $this->m('user')->where($w)->find();
		if($info){
			if($info['Status'] == -1){
				echo 3;//删除的用户
				exit;
			}else{
				if(isset($info['Cid'])){
					$company = $this->m('company')->where("Id = " . $info['Cid'])->find();
				}else{
					$company['CompanyName']="";
				}
				$user = array(
					'id' => $info['Id'],
					'cid' => $info['Cid'],
					'pid' => $info['Pid'],
					'phone' => $info['Phone'],
					'CompanyName' => $company['CompanyName'],
                    'UserPhoto' => $info['UserPhoto'],
				);
				session('UserInfo',$user);
				$this->U = session('UserInfo');
				echo 4;
				exit;
				
			}
		}else{
			echo 5;
			exit;
		}
	}

	public function ScSweepstakesNumber(){//随机6位不重复的数字
		static $arr=array();
		  if(count($arr)<6){
				$num = rand(1,9);
				if(in_array($num,$arr)){
					$this->ScSweepstakesNumber();

					
				}else{
					
					array_push($arr,$num);
					$this->ScSweepstakesNumber();

				}
				
			}
		return (int)implode($arr);

	}
	public function SknHq($num){//判断数据库总是否存在此数
		$ifcz = $this->m("sweepstakes")->where("SweepstakesNumber = ".$num)->find();
		if($ifcz){
			$num = $this->ScSweepstakesNumber();
			$this->SknHq($num);
		}
		return $num;
	}

}